import json

import pymysql
from selenium import webdriver

def create_chrom_driver(*, headless=False):
    """创建Chrome浏览器对象"""
    options = webdriver.ChromeOptions()
    options.add_experimental_option("detach", True)
    if headless:
        options.add_argument('--headless')
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)
    browser = webdriver.Chrome(options=options)
    browser.execute_cdp_cmd(
        'Page.addScriptToEvaluateOnNewDocument',
        {'source': 'Object.defineProperty(navigator,"webdriver",{get:() => undefined})'}
    )
    return browser

def add_cookies(browser, cookie_file):
    """将浏览器对象写入指定cookies信息"""
    with open(cookie_file, 'r') as file:
        cookie_list = json.load(file)
        for cookie_dict in cookie_list:
            if cookie_dict['secure']:
                browser.add_cookie(cookie_dict)

# 创建mysql连接
db = pymysql.connect(
    user='用户名',
    password='密码',
    host='主机',
    port='端口号',
    database='数据库名'
)

# 创建游标
cursor = db.cursor()

# 初始化方法
def dbsql(sql_table):
    # 创建数据库表
    sql_table = sql_table
    cursor.execute(sql_table)
    print('数据表创建完成!')

# 定义存储函数（存到mysql）
def save_mysql(insert_sql, summary):
    cursor.execute(insert_sql, summary)
    # 提交到数据库执行
    db.commit()

# 关闭mysql连接的方法
def close_mysql():
    # 关闭游标
    cursor.close()
    # 关闭连接
    db.close()
